package tool

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"web_app/pak/trans"
)

const secret = "XNCSHUIDFDFGSFGSFIFSFS"

// IsDevelopment 判断是否是开发模式
func IsDevelopment() bool {
	return viper.GetString("app.mode") == "dev"
}

//ReturnVerificationTool  参数校验返回
func ReturnVerificationTool(err error, c *gin.Context) {
	zap.L().Error("with invalid param", zap.Error(err))
	validationErrors, ok := err.(validator.ValidationErrors)
	if !ok {
		Error(c, "请求参数错误")
		return
	}
	Error(c, trans.RemoveTopStruct(validationErrors.Translate(trans.Trans)))
	return
}

//EncryptPassword 加密
func EncryptPassword(password string) string {
	h := md5.New()
	h.Write([]byte(secret))
	sum := h.Sum([]byte(password))
	return hex.EncodeToString(sum)
}

func GetCurrentUserId(c *gin.Context) (userId int64, err error) {
	uid, ok := c.Get("userId")
	if !ok {
		err = errors.New("用户未登陆")
		return
	}

	userId, ok = uid.(int64)
	if !ok {
		err = errors.New("用户未登陆")
		return
	}

	return
}
